package com.zjh.service.user;

import com.zjh.dao.BaseDao;
import com.zjh.dao.user.UserDao;
import com.zjh.dao.user.UserDaoImpl;
import com.zjh.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public UserServiceImpl() {
        userDao = new UserDaoImpl();
    }

    @Override
    public User Login(String name) {
        Connection connection = null;
        User user = null;

        connection = BaseDao.getConnection();
        try {
            user = userDao.login(connection, name);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            BaseDao.CloseResource(connection, null, null);
        }

        return user;
    }

    @Override
    public Boolean Register(User user) {
        Boolean flag = false;
        Connection connection = null;
        try {
            //获得连接
            connection = BaseDao.getConnection();
            //开启JDBC事务管理
            connection.setAutoCommit(false);
            int updateRows = userDao.register(connection, user);
            connection.commit();
            if (updateRows > 0) {
                flag = true;
                System.out.println("add success!");
            } else {
                System.out.println("add failed!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                System.out.println("rollback==");
                //失败就回滚
                connection.rollback();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        } finally {
            //在service层进行connection连接的关闭
            BaseDao.CloseResource(connection, null, null);
        }
        return flag;
    }
}
